package com.yangyang.rpc.core.netcom.netty.client;

import com.yangyang.rpc.core.registry.zookeeper.ZkServiceDiscovery;
import com.yangyang.rpc.core.serialize.Serializer;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.jboss.netty.util.internal.ConcurrentHashMap;

/**
 * Created by chenshunyang on 2016/11/22.
 */
public class NettyClientPool{

    private GenericObjectPool<NettyClientPoolProxy> pool;

    private static ConcurrentHashMap<String, NettyClientPool> clientPoolMap = new ConcurrentHashMap<String, NettyClientPool>();

    public NettyClientPool(String host ,int port,Serializer serializer){
        pool = new GenericObjectPool<NettyClientPoolProxy>(new NettyClientPoolFactory(host, port, serializer));
        pool.setConfig(new NettyClientPoolConfig());
    }

    private GenericObjectPool<NettyClientPoolProxy> getPool() {
        return this.pool;
    }

    public static  GenericObjectPool<NettyClientPoolProxy> getPool(String serverAddress, Serializer serializer, String className) {

        // valid serverAddress 传入为空，根据className从已有的zk中获取
        if (serverAddress == null || serverAddress.trim().length()==0) {
            serverAddress = ZkServiceDiscovery.discover(className);
        }

        if (serverAddress == null || serverAddress.trim().length() == 0) {
            throw new IllegalArgumentException(">>>>>>>>>>>> serverAddress is null");
        }

        // get from pool
        NettyClientPool clientPool = clientPoolMap.get(serverAddress);
        if (clientPool != null) {
            return clientPool.getPool();
        }

        // init pool
        String[] array = serverAddress.split(":");
        String host = array[0];
        int port = Integer.parseInt(array[1]);

        clientPool = new NettyClientPool(host, port, serializer);
        clientPoolMap.put(serverAddress,clientPool);
        return clientPool.getPool();
    }


}
